<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/18
 * Time: 11:52
 */

namespace app\manage\controller;
class HousePic extends Base
{
    private $house_id;
    public function _initialize(){
        $this->house_id = input('param.house_id/d',0);
        $this->param_extra = ['house_id'=>$this->house_id];
        parent::_initialize();
        $this->mod = model('house_pic');
        $this->sort = 'ordid';
        $this->order = 'asc,id desc';
        $this->getHouseName();
        $this->assign('house_id',$this->house_id);
    }
    //搜索
    public function _search(){
        $map['house_id'] = $this->house_id;
        ($keyword = input('get.keyword')) && $map['title'] = ['like', '%'.$keyword.'%'];
        $status = -1;
        if(isset($_GET['status']) && $_GET['status'] !== ''){
            $status = input('get.status/d');
        }
        $status>=0 && $map['status'] = ['eq',$status];
        ($cate_id = input('get.cate_id/d',0)) && $map['cate_id'] = $cate_id;
        $this->assign('search', array(
            'status'  => $status,
            'keyword' => $keyword,
            'cate_id' => $cate_id
        ));
        return $map;
    }
    //添加图片
    public function addDo(){
       $this->addPic();
    }
    //删除图片
    public function delete(){
        \app\common\model\HousePic::event('after_delete',function($obj){
            if($obj->img){
                @unlink('.'.$obj->img);
            }
        });
        parent::delete();
    }
    /**
     * @param $obj
     * 添加图片
     */
    private function addPic(){
        $house_id = input('post.house_id');
        $cate_id  = input('post.cate_id');
        $status   = input('post.status/d',1);
        $cate_name = input('post.cate_name');
        if(isset($_POST['pic']) && !empty($_POST['pic'])) {
            $insert = [];
            $images = $_POST['pic'];
            foreach ($images['pic'] as $key => $v) {
                $insert[] = [
                    'img' => $v,
                    'title' => $images['alt'][$key],
                    'create_time'=>time(),
                    'house_id' => $house_id,
                    'cate_id' => $cate_id,
                    'status' => $status,
                    'cate_name' => $cate_name
                ];
            }
            if($insert){
               if($this->mod->saveAll($insert)){
                   model('house')->where(['id'=>$house_id])->setInc('pic_count',count($insert));
                   $this->success('添加图片成功');
               }else{
                   $this->error('添加图片失败');
               }
            }
        }else{
            $this->error('请选择图片');
        }
    }
    //获取楼盘名称
    private function getHouseName(){
        $title = model('house')->where(['id'=>$this->house_id])->value('title');
        $this->assign('house_title',$title);
    }
}